<template>
  <view class="chat-container">
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="header-center">
        <image class="other-avatar" :src="otherUserAvatar" mode="aspectFill" />
        <view class="header-info">
          <text class="other-name">{{ otherUserName }}</text>
          <text class="online-status" :class="{ 'connected': isWebSocketConnected, 'disconnected': !isWebSocketConnected }">
            {{ isWebSocketConnected ? '在线' : '离线' }}
          </text>
        </view>
      </view>
      <view class="header-right">
        <view class="more-btn" @click="showMoreOptions">
          <text class="more-icon">⋯</text>
        </view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y :scroll-top="scrollTop" scroll-with-animation>
      <!-- 加载状态 -->
      <view class="loading-container" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 消息项 -->
      <view class="message-item" v-for="(message, index) in messageList" :key="message.id || index" :class="{ 'own-message': message.isOwn }">
        <!-- 消息内容 -->
        <view class="message-content">
          <view class="message-bubble" :class="{ 'own-bubble': message.isOwn }" @longpress="onMessageLongPress(message, index)">
            <text class="message-text">{{ message.content }}</text>
            <!-- 消息状态 -->
            <view class="message-status" v-if="message.isOwn && message.status">
              <text class="status-icon" v-if="message.status === 'sending'">⏳</text>
              <text class="status-icon" v-else-if="message.status === 'sent'">✓</text>
              <text class="status-icon error" v-else-if="message.status === 'failed'">❌</text>
            </view>
          </view>
          <text class="message-time">{{ formatMessageTime(message.timestamp) }}</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-messages" v-if="!loading && messageList.length === 0">
        <text class="empty-text">暂无消息</text>
        <text class="empty-hint">发送第一条消息开始聊天吧！</text>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-container">
        <view class="input-tools">
          <view class="tool-btn" @click="selectEmoji">
            <text class="tool-icon">😊</text>
          </view>
          <view class="tool-btn" @click="selectImage">
            <text class="tool-icon">📷</text>
          </view>
        </view>
        <view class="input-wrapper">
          <textarea 
            class="message-input" 
            v-model="inputMessage" 
            placeholder="输入消息..." 
            :auto-height="true"
            :maxlength="500"
            @focus="onInputFocus"
            @blur="onInputBlur"
            @input="onInputChange"
            @confirm="sendMessage"
          />
          <!-- 字数统计 -->
          <view class="char-count" v-if="inputMessage.length > 400">
            <text class="count-text" :class="{ 'warning': inputMessage.length > 450 }">
              {{ inputMessage.length }}/500
            </text>
          </view>
        </view>
        <view class="send-btn" :class="{ 'active': canSend, 'disabled': !canSend }" @click="sendMessage">
          <text class="send-text">{{ sendButtonText }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { MessageAPI } from '@/utils/api'
import { AuthUtils } from '@/utils/auth'
import { websocketManager } from '@/utils/websocket'

// 页面参数
const conversationId = ref('')
const otherUserId = ref('')
const otherUserName = ref('')
const otherUserAvatar = ref('/static/logo.png')

// 用户信息
const userInfo = computed(() => AuthUtils.getUserInfo())
const userAvatar = computed(() => userInfo.value?.avatar || '/static/logo.png')

// 消息相关
interface Message {
  id?: string
  content: string
  timestamp: string
  isOwn: boolean
  senderId: string
  status?: 'sending' | 'sent' | 'failed' // 消息状态
  type?: 'text' | 'image' | 'emoji' // 消息类型
}

const messageList = ref<Message[]>([])
const inputMessage = ref('')
const loading = ref(false)
const scrollTop = ref(0)
const isSending = ref(false)

// WebSocket相关状态
const isWebSocketConnected = ref(false)
const webSocketError = ref('')

// WebSocket监听器清理函数
let messageUnsubscribe: (() => void) | null = null
let connectionUnsubscribe: (() => void) | null = null
let errorUnsubscribe: (() => void) | null = null

// 计算属性：是否可以发送
const canSend = computed(() => {
  return inputMessage.value.trim().length > 0 && !isSending.value
})

// 计算属性：发送按钮文本
const sendButtonText = computed(() => {
  if (isSending.value) return '发送中'
  return '发送'
})

// 格式化消息时间
const formatMessageTime = (timestamp: string): string => {
  const messageTime = new Date(timestamp)
  const now = new Date()
  const diffMs = now.getTime() - messageTime.getTime()
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  
  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else {
    return messageTime.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit',
      hour12: false 
    })
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  scrollTop.value = 999999
}

// 加载消息列表
const loadMessages = async (page: number = 1, limit: number = 20) => {
  if (!conversationId.value) return
  
  try {
    loading.value = true
    
    // 调用获取消息列表的API
    const response = await MessageAPI.getMessages(conversationId.value, { page, limit })
    
    if (response.code === 200 && response.data) {
      const { messages } = response.data
      
      // 转换API数据格式为本地Message格式
      const convertedMessages: Message[] = messages.map((apiMessage: any) => ({
        id: apiMessage.id.toString(),
        content: apiMessage.content,
        timestamp: apiMessage.createdAt,
        isOwn: apiMessage.senderId === userInfo.value?.userId,
        senderId: apiMessage.senderId,
        status: 'sent' as const,
        type: 'text' as const
      }))
      
      // 如果是第一页，替换消息列表；否则追加到前面（用于分页加载历史消息）
      if (page === 1) {
        messageList.value = convertedMessages
      } else {
        messageList.value = [...convertedMessages, ...messageList.value]
      }
      
      await scrollToBottom()
    }
  } catch (error: any) {
    console.error('加载消息失败:', error)
    
    // 如果是网络错误或服务器错误，显示模拟数据作为fallback
    if (page === 1) {
      console.log('使用模拟数据作为fallback')
      const mockMessages: Message[] = [
        {
          id: '1',
          content: '你好！',
          timestamp: new Date(Date.now() - 300000).toISOString(),
          isOwn: false,
          senderId: otherUserId.value,
          status: 'sent',
          type: 'text'
        },
        {
          id: '2',
          content: '你好，最近怎么样？',
          timestamp: new Date(Date.now() - 240000).toISOString(),
          isOwn: true,
          senderId: userInfo.value?.userId || '',
          status: 'sent',
          type: 'text'
        },
        {
          id: '3',
          content: '还不错，你呢？',
          timestamp: new Date(Date.now() - 180000).toISOString(),
          isOwn: false,
          senderId: otherUserId.value,
          status: 'sent',
          type: 'text'
        }
      ]
      messageList.value = mockMessages
      await scrollToBottom()
    }
    
    uni.showToast({
      title: error.message || '加载消息失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!canSend.value || isSending.value || !conversationId.value) return
  
  isSending.value = true
  
  const content = inputMessage.value.trim()
  const tempMessage: Message = {
    content,
    timestamp: new Date().toISOString(),
    isOwn: true,
    senderId: userInfo.value?.userId || '',
    status: 'sending',
    type: 'text'
  }
  
  // 立即添加到消息列表
  messageList.value.push(tempMessage)
  inputMessage.value = ''
  await scrollToBottom()
  
  try {
    // 使用WebSocket发送消息
    if (isWebSocketConnected.value) {
      await websocketManager.sendMessage(conversationId.value, content)
      
      // WebSocket发送成功，消息状态会通过new_message事件更新
      // 这里暂时保持sending状态，等待服务器确认
      console.log('WebSocket消息发送成功')
    } else {
      // WebSocket未连接，回退到HTTP API
      console.log('WebSocket未连接，使用HTTP API发送消息')
      const response = await MessageAPI.sendMessage(conversationId.value, content)
      
      if (response.code === 200 && response.data) {
        const { message: apiMessage } = response.data
        
        // 更新临时消息为服务器返回的消息数据
        const messageIndex = messageList.value.length - 1
        if (messageIndex >= 0) {
          messageList.value[messageIndex] = {
            id: apiMessage.id.toString(),
            content: apiMessage.content,
            timestamp: apiMessage.createdAt,
            isOwn: true,
            senderId: apiMessage.senderId,
            status: 'sent',
            type: 'text'
          }
        }
        
        console.log('HTTP API消息发送成功:', apiMessage)
      }
    }
    
  } catch (error: any) {
    console.error('发送消息失败:', error)
    
    // 发送失败，更新消息状态
    const messageIndex = messageList.value.length - 1
    if (messageIndex >= 0) {
      messageList.value[messageIndex].status = 'failed'
    }
    
    // 显示错误提示
    let errorMessage = '发送失败'
    if (error.message) {
      if (error.message.includes('400')) {
        errorMessage = '消息内容无效'
      } else if (error.message.includes('404')) {
        errorMessage = '会话不存在或无权限'
      } else if (error.message.includes('500')) {
        errorMessage = '服务器错误，请稍后重试'
      } else {
        errorMessage = error.message
      }
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'none'
    })
    
  } finally {
    isSending.value = false
  }
}

// 输入框事件
const onInputFocus = () => {
  setTimeout(() => {
    scrollToBottom()
  }, 300)
}

const onInputBlur = () => {
  // 输入框失焦处理
}

const onInputChange = () => {
  // 输入内容变化处理，可以在这里添加打字状态等功能
}

// 长按消息事件
const onMessageLongPress = (message: Message, index: number) => {
  const itemList = ['复制', '删除']
  if (message.status === 'failed') {
    itemList.unshift('重新发送')
  }
  
  uni.showActionSheet({
    itemList,
    success: (res) => {
      const action = itemList[res.tapIndex]
      switch (action) {
        case '复制':
          uni.setClipboardData({
            data: message.content,
            success: () => {
              uni.showToast({
                title: '已复制',
                icon: 'success'
              })
            }
          })
          break
        case '删除':
          messageList.value.splice(index, 1)
          break
        case '重新发送':
          if (message.isOwn) {
            message.status = 'sending'
            // 重新发送逻辑
            setTimeout(() => {
              message.status = 'sent'
            }, 1000)
          }
          break
      }
    }
  })
}

// 工具按钮事件
const selectEmoji = () => {
  uni.showToast({
    title: '表情功能开发中',
    icon: 'none'
  })
}

const selectImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      console.log('选择图片:', res.tempFilePaths)
      uni.showToast({
        title: '图片发送功能开发中',
        icon: 'none'
      })
    }
  })
}

// 更多选项
const showMoreOptions = () => {
  uni.showActionSheet({
    itemList: ['查看资料', '清空聊天记录', '举报'],
    success: (res) => {
      console.log('选择了第' + (res.tapIndex + 1) + '个选项')
    }
  })
}

// 返回
const goBack = () => {
  uni.switchTab({
    url: '/pages/message'
  })
}

// 初始化WebSocket连接和监听器
const initWebSocket = async () => {
  try {
    console.log('=== 初始化WebSocket ===', {
      conversationId: conversationId.value,
      userId: userInfo.value?.userId
    })
    
    // 监听连接状态
    connectionUnsubscribe = websocketManager.onConnection((connected) => {
      console.log('WebSocket连接状态变化:', connected)
      isWebSocketConnected.value = connected
      if (connected) {
        webSocketError.value = ''
        console.log('WebSocket连接成功，准备加入会话')
        // 连接成功后加入会话
        if (conversationId.value) {
          console.log('自动加入会话:', conversationId.value)
          joinConversation()
        } else {
          console.warn('会话ID为空，无法加入会话')
        }
      } else {
        console.log('WebSocket连接断开')
      }
    })

    // 监听错误
    errorUnsubscribe = websocketManager.onError((error) => {
      webSocketError.value = error.message || '连接错误'
      console.error('WebSocket错误:', error)
      uni.showToast({
        title: error.message || 'WebSocket连接错误',
        icon: 'none'
      })
    })

    // 监听新消息
    messageUnsubscribe = websocketManager.onMessage((message) => {
      console.log('=== 收到WebSocket消息 ===', message)
      handleNewMessage(message)
    })

    // 获取当前连接状态
    const currentStatus = websocketManager.getConnectionStatus()
    isWebSocketConnected.value = currentStatus
    console.log('当前WebSocket连接状态:', currentStatus)
    
  } catch (error) {
    console.error('WebSocket初始化失败:', error)
  }
}

// 加入会话
const joinConversation = async () => {
  console.log('=== 尝试加入会话 ===', {
    conversationId: conversationId.value,
    isWebSocketConnected: isWebSocketConnected.value,
    currentConversationId: websocketManager.getCurrentConversationId()
  })
  
  if (!conversationId.value) {
    console.error('会话ID为空，无法加入会话')
    return
  }
  
  if (!isWebSocketConnected.value) {
    console.error('WebSocket未连接，无法加入会话')
    return
  }
  
  try {
    console.log('开始加入会话:', conversationId.value)
    await websocketManager.joinConversation(conversationId.value)
    console.log('✅ 成功加入会话:', conversationId.value)
  } catch (error) {
    console.error('❌ 加入会话失败:', error)
    uni.showToast({
      title: '加入会话失败',
      icon: 'none'
    })
  }
}

// 处理新消息
const handleNewMessage = (message: any) => {
  console.log('=== 处理新消息 ===', {
    message,
    currentConversationId: conversationId.value,
    messageConversationId: message.conversationId,
    currentUserId: userInfo.value?.userId,
    messageSenderId: message.senderId
  })
  
  // 检查消息是否属于当前会话
  if (message.conversationId.toString() !== conversationId.value) {
    console.log('消息不属于当前会话，忽略', {
      messageConversationId: message.conversationId,
      currentConversationId: conversationId.value
    })
    return
  }
  
  // 转换WebSocket消息格式为本地Message格式
  const newMessage: Message = {
    id: message.id.toString(),
    content: message.content,
    timestamp: message.createdAt,
    isOwn: message.senderId === userInfo.value?.userId,
    senderId: message.senderId,
    status: 'sent',
    type: 'text'
  }
  
  console.log('转换后的消息:', newMessage)

  // 如果是自己发送的消息，更新对应的临时消息状态
  if (newMessage.isOwn) {
    console.log('这是自己发送的消息，查找临时消息进行更新')
    const tempMessageIndex = messageList.value.findIndex(
      msg => msg.status === 'sending' && msg.content === newMessage.content
    )
    if (tempMessageIndex >= 0) {
      console.log('找到临时消息，更新状态', tempMessageIndex)
      // 更新临时消息为服务器确认的消息
      messageList.value[tempMessageIndex] = newMessage
      return
    } else {
      console.log('未找到对应的临时消息')
    }
  }

  // 添加新消息到列表
  console.log('添加新消息到列表，当前消息数量:', messageList.value.length)
  messageList.value.push(newMessage)
  console.log('添加后消息数量:', messageList.value.length)
  scrollToBottom()
}

// 页面加载
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}
  
  conversationId.value = options.conversationId || ''
  otherUserId.value = options.otherUserId || ''
  otherUserName.value = decodeURIComponent(options.otherUserName || '未知用户')
  otherUserAvatar.value = decodeURIComponent(options.otherUserAvatar || '/static/logo.png')
  
  console.log('聊天页面参数:', {
    conversationId: conversationId.value,
    otherUserId: otherUserId.value,
    otherUserName: otherUserName.value,
    otherUserAvatar: otherUserAvatar.value
  })
  
  // 检查登录状态
  if (!AuthUtils.isLoggedIn()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    uni.reLaunch({
      url: '/pages/login'
    })
    return
  }
  
  // 初始化WebSocket
  initWebSocket()
  
  // 加载历史消息
  loadMessages()
})

// 页面卸载时清理资源
onUnmounted(() => {
  // 离开当前会话
  if (conversationId.value && isWebSocketConnected.value) {
    websocketManager.leaveConversation(conversationId.value)
  }
  
  // 清理监听器
  if (messageUnsubscribe) {
    messageUnsubscribe()
    messageUnsubscribe = null
  }
  if (connectionUnsubscribe) {
    connectionUnsubscribe()
    connectionUnsubscribe = null
  }
  if (errorUnsubscribe) {
    errorUnsubscribe()
    errorUnsubscribe = null
  }
})
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 聊天头部 */
.chat-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: calc(120rpx + env(safe-area-inset-top));
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: env(safe-area-inset-top) 30rpx 0;
  border-bottom: 1rpx solid #e5e5e5;
  z-index: 100;
}

.header-left {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  color: #007AFF;
  font-weight: bold;
}

.header-center {
  flex: 1;
  display: flex;
  align-items: center;
  margin-left: 20rpx;
}

.other-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
}

.header-info {
  display: flex;
  flex-direction: column;
}

.other-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 4rpx;
}

.online-status {
  font-size: 24rpx;
  transition: color 0.3s ease;
}

.online-status.connected {
  color: #52c41a;
}

.online-status.disconnected {
  color: #ff4d4f;
}

.header-right {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-icon {
  font-size: 36rpx;
  color: #666666;
}

/* 消息列表 */
.message-list {
  flex: 1;
  padding: calc(140rpx + env(safe-area-inset-top)) 30rpx calc(200rpx + env(safe-area-inset-bottom));
  overflow-y: auto;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

.empty-messages {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 16rpx;
}

.empty-hint {
  font-size: 26rpx;
  color: #999999;
}

.message-item {
    display: flex;
    margin-bottom: 30rpx;
    padding-right:60rpx;
    animation: messageSlideIn 0.3s ease-out;
  }

  /* 对方消息默认左对齐 */
  .message-item:not(.own-message) {
    justify-content: flex-start;
  }

  /* 我的消息右对齐 */
  .message-item.own-message {
    justify-content: flex-end;
  }

  @keyframes messageSlideIn {
    from {
      opacity: 0;
      transform: translateY(20rpx);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .message-content {
    max-width: 70%;
    display: flex;
    flex-direction: column;
  }

  /* 我的消息内容右对齐 */
  .own-message .message-content {
    align-items: flex-end;
  }

  .message-bubble {
    background-color: #ffffff;
    padding: 24rpx 28rpx;
    border-radius: 24rpx;
    margin-bottom: 8rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    word-wrap: break-word;
    display: flex;
    align-items: center;
    max-width: 100%;
  }

  .message-bubble.own-bubble {
    background-color: #007AFF;
  }

  .message-text {
    font-size: 28rpx;
    color: #333333;
    line-height: 1.4;
    word-wrap: break-word;
    flex: 1;
  }

  .own-bubble .message-text {
    color: #ffffff;
  }

  /* 消息状态 */
  .message-status {
    margin-left: 12rpx;
    display: flex;
    align-items: center;
    flex-shrink: 0;
  }

  .status-icon {
    font-size: 20rpx;
    opacity: 0.7;
  }

  .status-icon.error {
    opacity: 1;
  }

  .message-time {
    font-size: 22rpx;
    color: #999999;
    margin-top: 4rpx;
  }

  /* 我的消息时间右对齐 */
  .own-message .message-time {
    text-align: right;
  }

/* 输入区域 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-top: 1rpx solid #e5e5e5;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-container {
  display: flex;
  align-items: flex-end;
}

.input-tools {
  display: flex;
  margin-right: 20rpx;
}

.tool-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.tool-icon {
  font-size: 36rpx;
}

.input-wrapper {
  flex: 1;
  background-color: #f8f9fa;
  border-radius: 28rpx;
  padding: 20rpx 28rpx;
  margin-right: 20rpx;
  min-height: 56rpx;
  max-height: 240rpx;
  border: 2rpx solid transparent;
  transition: all 0.2s ease;
  position: relative;
}

.input-wrapper:focus-within {
  border-color: #007AFF;
  background-color: #ffffff;
}

/* 字数统计 */
.char-count {
  position: absolute;
  bottom: 8rpx;
  right: 12rpx;
  z-index: 1;
}

.count-text {
  font-size: 20rpx;
  color: #999999;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 2rpx 6rpx;
  border-radius: 8rpx;
}

.count-text.warning {
  color: #ff4d4f;
}

.message-input {
  width: 100%;
  font-size: 28rpx;
  color: #333333;
  background-color: transparent;
  border: none;
  outline: none;
  resize: none;
  line-height: 1.4;
}

.send-btn {
  width: 120rpx;
  height: 64rpx;
  background-color: #e5e5e5;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  transform: scale(1);
}

.send-btn:active {
  transform: scale(0.95);
}

.send-btn.active {
  background-color: #007AFF;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.send-btn.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-text {
  font-size: 28rpx;
  color: #999999;
  font-weight: 500;
}

.send-btn.active .send-text {
  color: #ffffff;
}
</style>